package com.ddone.controller;

import com.ddone.helper.JwtHelper;
import com.ddone.model.auth.SysUser;
import com.ddone.model.vo.LoginVo;
import com.ddone.model.vo.Result;
import com.ddone.model.vo.ResultCodeEnum;
import com.ddone.service.SysUserService;
import com.ddone.util.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author ddone
 * @date 2024/3/28-09:29
 */
@RestController
@RequestMapping("/index")
@Api(value = "后台管理首页API",tags = {"首页"})
public class IndexController {

    @Autowired
    private SysUserService userService;

    @PostMapping("/login")
    @ApiOperation("登录接口")
    public Result<Object> login(@RequestBody LoginVo loginVo) {
        // 根据前端传过来的信息进行登录
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();

        // 查询数据库
        SysUser sysUser = userService.getByUsername(username);

        if (Objects.isNull(sysUser)) {
            return Result.build(null, ResultCodeEnum.ACCOUNT_ERROR);
        }

        // 默认 admin 111111
        if (!MD5.encrypt(password).equals(sysUser.getPassword())) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }

        if(sysUser.getStatus() == 0){
            return Result.build(null, ResultCodeEnum.ACCOUNT_STOP);
        }

        // 登录后将token 返回给前端
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(sysUser.getId(),sysUser.getUsername()));
        return Result.ok(map);
    }

    @GetMapping("/info")
    @ApiOperation("查询登录的用户信息")
    public Result<Object> info(@RequestHeader String token){
        Long userId = JwtHelper.getUserId(token);
        // 按照token查询用户信息
        // Map<String, Object> map = new HashMap<>();
        // map.put("roles","[admin]");
        // map.put("name","admin");
        // map.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        // map.put("buttons", new ArrayList<>());
        // map.put("routers", new ArrayList<>());

        Map<String,Object> userInfo = userService.getUserInfoByUserId(userId);

        return Result.ok(userInfo);
    }

    @PostMapping("/logout")
    @ApiOperation("登出接口")
    public Result<Object> logout(){
        return Result.ok();
    }
}
